﻿using MiniFox.Platform.State;
using MiniFox.Scripting;
using System.Text.RegularExpressions;

namespace MiniFox.Platform.Scripting
{
    /// <summary>
    /// 
    /// </summary>
    public static class ScriptingExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="stateManagement"></param>
        /// <returns></returns>
        public static string Resolve(this string input, IStateManagement stateManagement)
        {

            string result = ScriptEngine.REG_EXPRESSION.Replace(input, (Match match) =>
            {
                var func_call = match.Groups[1].Value;
                Match match_func = ScriptEngine.REG_FUNCTION.Match(func_call);
                if (!match_func.Success) return string.Empty;
                var func_name = match_func.Groups[0].Value;
                //函数实例
                var function = ScriptEngine.Container.Functions[func_name];
                if (function is StateFunctionBase)
                {
                    ((StateFunctionBase)function).StateManagement = stateManagement;
                }
                Match match_args = ScriptEngine.REG_ARGUMENTS.Match(func_call);
                List<object> parameters = new List<object>();
                if (match_args.Success)
                {
                    var str_args = match_args.Groups[1].Value;
                    string[] arguments = str_args.Split(',');
                    foreach (var argument in arguments)
                    {
                        parameters.Add(argument.Trim());
                    }
                }
                //执行函数得到结果
                object val = function.Execute(parameters.ToArray());
                return val.ToString();
            });

            //替换命令
            return result;
        }
    }
}
